#include "hoursbyperson.h"
#include "ui_hoursbyperson.h"
#include "mainwindow.h"
#include "xlsxdocument.h"
#include <QDate>
#include <QMessageBox>
#include <QFileInfo>
#include <QFileDialog>
#include <QToolTip>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>


HoursByPerson::HoursByPerson(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HoursByPerson)
{
    ui->setupUi(this);
    this->setLayout(ui->gridLayout);
    QDate curdate = QDate::currentDate();

    ui->de_startDate->setMaximumDate(curdate);
    ui->de_startDate->setMinimumDate(curdate.addDays(-180));
    ui->de_endDate->setMinimumDate(curdate.addDays(-180));
    ui->de_endDate->setMaximumDate(curdate);

    ui->cb_quickQuery->addItem("上周");
    ui->cb_quickQuery->addItem("本周");
    ui->cb_quickQuery->addItem("本月");
    ui->cb_quickQuery->addItem("上月");

    //ui->horizontalLayout->setSpacing(15);//设置控件之间的间隔

    m_totalHoursModel = new QStandardItemModel();
    ui->tv_tatolHours->setModel(m_totalHoursModel);
    QStringList tabHeadersTotalName;
    tabHeadersTotalName << "团队名称" << "姓名" << "工时数";
    m_totalHoursModel->setHorizontalHeaderLabels(tabHeadersTotalName);
    ui->tv_tatolHours->horizontalHeader()->setFixedHeight(35);
    ui->tv_tatolHours->verticalHeader()->setDefaultSectionSize(25);//设置列的行高
    ui->tv_tatolHours->horizontalHeader()->setStyleSheet("QHeaderView::section {background-color:#1E90FF;}");
    ui->tv_tatolHours->setAlternatingRowColors( true );//交替颜色背景
    ui->tv_tatolHours->setStyleSheet("alternate-background-color:rgb(135,206,235);");
    ui->tv_tatolHours->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tv_tatolHours->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tv_tatolHours->setColumnWidth(1, 100);//设置列宽
    ui->tv_tatolHours->setColumnWidth(2, 50);
    ui->tv_tatolHours->setColumnWidth(3, 50);
    //-------------------------------------------------------------------------------------------------------------
    m_detailHoursModel = new QStandardItemModel();
    ui->tv_detailHours->setModel(m_detailHoursModel);
    QStringList tabHeadersDetailName;
    tabHeadersDetailName << "项目名称" << "任务名称" << "任务状态"<<"填写日期" << "填写工时"<< "任务描述"<<"成本大类";
    m_detailHoursModel->setHorizontalHeaderLabels(tabHeadersDetailName);
    ui->tv_detailHours->horizontalHeader()->setFixedHeight(35);
    ui->tv_detailHours->verticalHeader()->setDefaultSectionSize(25);
    ui->tv_detailHours->horizontalHeader()->setStyleSheet("QHeaderView::section {background-color:#1E90FF;}");
    ui->tv_detailHours->setAlternatingRowColors( true );
    ui->tv_detailHours->setStyleSheet("alternate-background-color:rgb(135,206,235);");
    ui->tv_detailHours->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tv_detailHours->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tv_detailHours->setColumnWidth(0, 160);
    ui->tv_detailHours->setColumnWidth(1, 320);
    ui->tv_detailHours->setColumnWidth(2, 60);
    ui->tv_detailHours->setColumnWidth(3, 80);
    ui->tv_detailHours->setColumnWidth(4, 60);
    ui->tv_detailHours->setColumnWidth(5, 320);
    ui->tv_detailHours->setColumnWidth(6, 200);
    ui->tv_detailHours->setMouseTracking(true);
    connect(ui->tv_detailHours,SIGNAL(entered(QModelIndex)),this,SLOT(ShowTooltip(QModelIndex)));
    //-------------------------------------------------------------------------------------------------------------
    m_holidayHoursModel = new QStandardItemModel();
    ui->tv_holidayInfo->setModel(m_holidayHoursModel);
    QStringList tabHeadersHolidayName;
    tabHeadersHolidayName << "姓名" << "请假类型" << "审批状态"<<"审批结果" << "开始时间"<< "结束时间"<<"时长";

    m_holidayHoursModel->setHorizontalHeaderLabels(tabHeadersHolidayName);
    ui->tv_holidayInfo->horizontalHeader()->setFixedHeight(35);
    ui->tv_holidayInfo->verticalHeader()->setDefaultSectionSize(25);
    ui->tv_holidayInfo->horizontalHeader()->setStyleSheet("QHeaderView::section {background-color:#1E90FF;}");
    ui->tv_holidayInfo->setAlternatingRowColors( true );
    ui->tv_holidayInfo->setStyleSheet("alternate-background-color:rgb(135,206,235);");
    ui->tv_holidayInfo->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tv_holidayInfo->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tv_holidayInfo->setColumnWidth(0, 120);
    ui->tv_holidayInfo->setColumnWidth(1, 120);
    ui->tv_holidayInfo->setColumnWidth(2, 120);
    ui->tv_holidayInfo->setColumnWidth(3, 120);
    ui->tv_holidayInfo->setColumnWidth(4, 120);
    ui->tv_holidayInfo->setColumnWidth(5, 120);
    ui->tv_holidayInfo->setColumnWidth(6, 120);

    m_mwindow = static_cast<MainWindow *>(QWidget::parentWidget());
    //qDebug()<<m_mwindow->dbMySql->connStr;
}

HoursByPerson::~HoursByPerson()
{
    delete ui;
}


void HoursByPerson::on_cb_quickQuery_currentTextChanged(const QString &arg1)
{
    QDate date = QDate::currentDate();
    if(arg1 == "本周")
    {
        date = date.addDays(-date.dayOfWeek()+1);
        ui->de_startDate->setDate(date);
        ui->de_endDate->setDate(date.addDays(6));
    }
    else if(arg1 =="上周")
    {
        date = date.addDays(-date.dayOfWeek()+1);
        ui->de_startDate->setDate(date.addDays(-7));
        ui->de_endDate->setDate(date.addDays(-1));
    }
    else if(arg1 =="本月")
    {
        ui->de_startDate->setDate(QDate(date.year(),date.month(),1));
        ui->de_endDate->setDate(QDate(date.year(),date.month(),date.daysInMonth()));
    }
    else if(arg1 == "上月")
    {
        date = date.addMonths(-1);
        ui->de_startDate->setDate(QDate(date.year(),date.month(),1));
        ui->de_endDate->setDate(QDate(date.year(),date.month(),date.daysInMonth()));
    }

}


void HoursByPerson::on_bt_query_clicked()
{
    //MainWindow *mw = static_cast<MainWindow *>(QWidget::parentWidget());
    //qDebug()<<m_mwindow->dbMySql->connStr;
    QString sDate = ui->de_startDate->date().toString("yyyy-MM-dd");
    QString eDate = ui->de_endDate->date().toString("yyyy-MM-dd");

    QList<DeptDevTotalHours> hoursList = m_mwindow->dbMySql->getDeptDevTotalHours(sDate,eDate);
    int idx=0;

    for (const auto& value : hoursList) {
        //  qDebug() << value;
        m_totalHoursModel->setItem(idx, 0, new QStandardItem(value.teamName));
        m_totalHoursModel->setItem(idx, 1, new QStandardItem(value.userName));
        m_totalHoursModel->setItem(idx, 2, new QStandardItem(value.consumed));
        idx++;
    }

}


void HoursByPerson::on_bt_export_clicked()
{

    //xlsx导出
    QXlsx::Document xlsx;
    QStringList titleList;
    QString filePathName;
    QString defaultFileName = "人员工时汇总.xls";

    // 设置保存的默认文件名称
    QFileInfo fileinfo(defaultFileName);
    // 获取保存文件路径
    QFileDialog *fileDlg = new QFileDialog(this);
    fileDlg->setWindowTitle("保存文件");
    fileDlg->setAcceptMode(QFileDialog::AcceptSave);
    fileDlg->selectFile(defaultFileName);
    fileDlg->setNameFilter("Excel Files(*.xls *.xlsx)");
    fileDlg->setDefaultSuffix("xls");

    if (fileDlg->exec() != QDialog::Accepted)//点击保存
        return;

    filePathName = fileDlg->selectedFiles().at(0);

    // 保存文件添加后缀名
    fileinfo =  QFileInfo(filePathName);
    if (fileinfo.suffix() != "xls" && fileinfo.suffix() != "xlsx")
    {
        filePathName += ".xls";
    }

    // 设置excel表头（第一行数据）
    titleList <<"团队名称"<<"姓名"<<"工时数";

    for (int i = 0; i < titleList.size(); i++)
    {
        xlsx.write(1, i+1, titleList.at(i));//
        xlsx.setColumnWidth(i, 30);//第一行,20列宽
    }

    //开始写第n行数据

    for (int row = 0; row < ui->tv_tatolHours->model()->rowCount(); row++)
    {
        for (int col = 0; col < ui->tv_tatolHours->model()->columnCount(); col++)
        {
            QModelIndex index = ui->tv_tatolHours->model()->index(row, col);
            xlsx.write(row + 2, col + 1, ui->tv_tatolHours->model()->data(index).toString());
        }
    }
    // 最后，保存文件
    xlsx.saveAs(filePathName);
    QMessageBox::information(this, "提示","导出成功！");
}


void HoursByPerson::on_tv_tatolHours_doubleClicked(const QModelIndex &index)
{
    int idx =  ui->tv_tatolHours->selectionModel()->currentIndex().row();
    QStandardItem *item = m_totalHoursModel->item(idx,1);
    QString userName = item->text();

    QString sDate = ui->de_startDate->date().toString("yyyy-MM-dd");
    QString eDate = ui->de_endDate->date().toString("yyyy-MM-dd");
    //MainWindow *mw = static_cast<MainWindow *>(QWidget::parentWidget());
    QList<DevDetailHours> detailList = m_mwindow->dbMySql->getDevDetailHours(userName,sDate,eDate);
    QMap<QString, QString> prjcost = m_mwindow->dbMySql_1->getProjectCostInfo();
    m_detailHoursModel->removeRows(0,m_detailHoursModel->rowCount());
    idx=0;
    for (const auto& value : detailList) {
        //  qDebug() << value;
        m_detailHoursModel->setItem(idx, 0, new QStandardItem(value.projectName));
        m_detailHoursModel->setItem(idx, 1, new QStandardItem(value.taskName));
        m_detailHoursModel->setItem(idx, 2, new QStandardItem(value.taskStatus));
        m_detailHoursModel->setItem(idx, 3, new QStandardItem(value.writeDate));
        m_detailHoursModel->setItem(idx, 4, new QStandardItem(value.consumed));
        m_detailHoursModel->setItem(idx, 5, new QStandardItem(value.taskDesc));
        m_detailHoursModel->setItem(idx, 6, new QStandardItem(prjcost[value.projectName]));
        idx++;
    }

    QList<UserHolidayInfo> holidayList = m_mwindow->dbMySql_1->getUserAttendanceFrDb(userName,sDate,eDate);
    qDebug()<<"getUserAttendanceFrDb"<<userName<<holidayList.size();
    m_holidayHoursModel->removeRows(0,m_holidayHoursModel->rowCount());
    idx=0;
    for (const auto& value : holidayList) {
        //  qDebug() << value;
        m_holidayHoursModel->setItem(idx, 0, new QStandardItem(value.userName));
        m_holidayHoursModel->setItem(idx, 1, new QStandardItem(value.holidayType));
        m_holidayHoursModel->setItem(idx, 2, new QStandardItem(value.approverResult));
        m_holidayHoursModel->setItem(idx, 3, new QStandardItem(value.approverStatus));
        m_holidayHoursModel->setItem(idx, 4, new QStandardItem(value.startDate));
        m_holidayHoursModel->setItem(idx, 5, new QStandardItem(value.endDate));
        m_holidayHoursModel->setItem(idx, 6, new QStandardItem(value.housrs));
        idx++;
    }
}

void HoursByPerson::ShowTooltip(QModelIndex index)
{
    QToolTip::showText(QCursor::pos(),index.data().toString());
    return ;
}

QList<UserHolidayInfo> HoursByPerson::getUserHolidayInfo(QString &userName, QString &startDate, QString &endDate)
{
    //网络请求对象
    QNetworkRequest request;
    //网络请求地址
    QString sRequestUrl = "http://onlinetable.kpy.cloud/fusion/v1/datasheets/dsttAMxqNaWcDcKl3v/records?viewId=viw3pTrNCNmr7&fieldKey=name&";
    QString sReqParams ="filterByFormula=find(\""+userName+"\",{发起人姓名})&sort={\"field\":\"开始时间\",\"order\":\"desc\"}";
    request.setUrl(QUrl(sRequestUrl+sReqParams));
    QString tokenstr="Bearer uskmP5YxnGiOYpNKotnp1EF";
    request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json;charset=utf-8"));
    request.setRawHeader("Authorization",tokenstr.toLatin1());

    // 网络请求
    QNetworkAccessManager *accessManager = new QNetworkAccessManager();
    QNetworkReply *reply = accessManager->get(request);

    //事件循环
    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
    // 获取返回的数据

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    QString retStr = reply->readAll();
    reply->abort();
    accessManager->deleteLater();//不主动释放会在卸载DLL时造成耗时
    accessManager=NULL;

    return ParseJson(retStr);
//    QList<UserHolidayInfo> tholidayList;

//    UserHolidayInfo uhi;
//    uhi.userName=userName;
//    uhi.holidayType="调休";
//    uhi.approverResult="完成";
//    uhi.approverStatus="同意";
//    uhi.startDate="2024-01-25 09:30";
//    uhi.endDate="2024-01-25 10:30";
//    uhi.housrs="1小时";

//    tholidayList.append(uhi);
    //    return tholidayList;
}


void traverseJson(const QJsonValue &value) {
    QJsonObject obj;
    QJsonArray arr;
    switch (value.type()) {
    case QJsonValue::Null:
        qDebug() << "Value is null.";
        break;
    case QJsonValue::Bool:
        qDebug() << "Value is a bool: " << value.toBool();
        break;
    case QJsonValue::Double:
        qDebug() << "Value is a double: " << value.toDouble();
        break;
    case QJsonValue::String:
        qDebug() << "Value is a string: " << value.toString();
        break;
    case QJsonValue::Object:
        qDebug() << "Value is an object:";
        obj = value.toObject();
        for (auto it = obj.begin(); it != obj.end(); ++it) {
            qDebug() << "Key: " << it.key() << " Value: ";
            traverseJson(it.value()); // 递归遍历对象的每个值
        }
        break;
    case QJsonValue::Array:
        qDebug() << "Value is an array:";
        arr = value.toArray();
        for (int i = 0; i < arr.size(); ++i) {
            qDebug() << "Element at index " << i << ":";
            traverseJson(arr.at(i)); // 递归遍历数组的每个元素
        }
        break;
    default:
        qDebug() << "Unknown value type.";
    }
}
QList<UserHolidayInfo>  HoursByPerson::ParseJson(const QString &str)
{
    int totalrec;
    UserHolidayInfo uhi;
    QList<UserHolidayInfo> tholidayList;

    QJsonDocument jsonDoc = QJsonDocument::fromJson(str.toUtf8());
    // 检查文档是否有效
    if (!jsonDoc.isObject()) {
        qWarning() << "Invalid JSON document!";
        return tholidayList;
    }
    // 获取并解析JSON对象
    const QJsonObject &jsonObj = jsonDoc.object();
    //qDebug()<<str;

    if (!(jsonObj.contains("data") && jsonObj["data"].isObject()))
    {
        qWarning() << "not contains data object!";
        return tholidayList;
    }
    QJsonObject dataobj = jsonObj["data"].toObject();

    if (!(dataobj.contains("records") && dataobj["records"].isArray()))
    {
        qWarning() << "not contains records array!";
        return tholidayList;
    }

    const QJsonArray &arr = dataobj["records"].toArray();
        //qDebug()<<"records"<<arr.size();
        for (const auto &rec : arr)
        {

            QJsonObject recobj = rec.toObject();
            //qDebug()<<recobj;
            QJsonObject fieldobj = recobj["fields"].toObject();
            //qDebug()<<fieldobj;
            if (fieldobj.contains("发起人姓名") && fieldobj["发起人姓名"].isString())
                uhi.userName = fieldobj["发起人姓名"].toString();
            if (fieldobj.contains("审批状态") && fieldobj["审批状态"].isString())
                uhi.approverStatus = fieldobj["审批状态"].toString();
            if (fieldobj.contains("审批结果") && fieldobj["审批结果"].isString())
                uhi.approverResult = fieldobj["审批结果"].toString();
            if (fieldobj.contains("开始时间") && fieldobj["开始时间"].isString())
                uhi.startDate = fieldobj["开始时间"].toString();
            if (fieldobj.contains("结束时间") && fieldobj["结束时间"].isString())
                uhi.endDate = fieldobj["结束时间"].toString();
            if (fieldobj.contains("时长") && fieldobj["时长"].isString())
                uhi.housrs = fieldobj["时长"].toString();
            if (fieldobj.contains("请假类型") && fieldobj["请假类型"].isString())
                uhi.holidayType = fieldobj["请假类型"].toString();

            tholidayList.append(uhi);
        }

    return tholidayList;
}

void HoursByPerson::on_bt_exportByProject_clicked() {

    QString sDate = ui->de_startDate->date().toString("yyyy-MM-dd");
    QString eDate = ui->de_endDate->date().toString("yyyy-MM-dd");

    QList<DeptDevTotalHoursByProject> hoursProjectList = m_mwindow->dbMySql->getDeptDevTotalHoursByProject(sDate,eDate);

    //xlsx导出
    QXlsx::Document xlsx;
    QStringList titleList;
    QString filePathName;
    QString defaultFileName = "人员项目工时汇总-"+sDate+"-"+eDate+".xls";

    // 设置保存的默认文件名称
    QFileInfo fileinfo(defaultFileName);
    // 获取保存文件路径
    QFileDialog *fileDlg = new QFileDialog(this);
    fileDlg->setWindowTitle("保存文件");
    fileDlg->setAcceptMode(QFileDialog::AcceptSave);
    fileDlg->selectFile(defaultFileName);
    fileDlg->setNameFilter("Excel Files(*.xls *.xlsx)");
    fileDlg->setDefaultSuffix("xls");

    if (fileDlg->exec() != QDialog::Accepted)//点击保存
        return;

    filePathName = fileDlg->selectedFiles().at(0);

    // 保存文件添加后缀名
    fileinfo =  QFileInfo(filePathName);
    if (fileinfo.suffix() != "xls" && fileinfo.suffix() != "xlsx")
    {
        filePathName += ".xls";
    }

    // 设置excel表头（第一行数据）
    titleList <<"姓名"<<"工时数"<<"项目名称"<<"团队名称";
    int colcount =titleList.size();
    for (int i = 0; i < colcount; i++)
    {
        xlsx.write(1, i+1, titleList.at(i));//
        xlsx.setColumnWidth(i, 30);//第一行,20列宽
    }

    //开始写第n行数据
    int rowcount = hoursProjectList.size();
    DeptDevTotalHoursByProject task;
    for (int row = 0; row < rowcount; row++)
    {
        task = hoursProjectList.at(row);
        xlsx.write(row + 2, 1, task.userName);
        xlsx.write(row + 2, 2, task.consumed);
        xlsx.write(row + 2, 3, task.projectName);
        xlsx.write(row + 2, 4, task.teamName);
    }
    // 最后，保存文件
    xlsx.saveAs(filePathName);
    QMessageBox::information(this, "提示","导出成功！");
}
